package com.example.hello.util;

import io.minio.*;
import io.minio.messages.Bucket;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Profile("test") // 只在 test 配置文件激活时运行
public class MinioClientTest implements CommandLineRunner {

    private static final Logger logger = LogManager.getLogger(MinioClientTest.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${object.storage.bucket-name}")
    private String bucketName;

    @Override
    public void run(String... args) throws Exception {
        logger.info("开始测试 MinIO 客户端连接，存储桶名称: {}", bucketName);

        try {
            // 列出所有存储桶
            List<Bucket> buckets = minioClient.listBuckets();
            logger.info("存储桶列表:");
            for (Bucket bucket : buckets) {
                logger.info(" - {}", bucket.name());
            }

            // 检查指定存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(
                BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build()
            );
            logger.info("存储桶 {} {}", bucketName, bucketExists ? "存在" : "不存在");

            // 尝试上传一个测试文件
            String testContent = "这是一个测试文件";
            ByteArrayInputStream testData = new ByteArrayInputStream(
                testContent.getBytes(StandardCharsets.UTF_8)
            );

            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object("test/test.txt")
                    .stream(testData, testContent.length(), -1)
                    .contentType("text/plain")
                    .build()
            );
            logger.info("测试文件上传成功");

            // 获取文件信息
            StatObjectResponse stat = minioClient.statObject(
                StatObjectArgs.builder()
                    .bucket(bucketName)
                    .object("test/test.txt")
                    .build()
            );
            logger.info("文件信息: 大小={}, 类型={}", stat.size(), stat.contentType());

            // 删除测试文件
            minioClient.removeObject(
                RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object("test/test.txt")
                    .build()
            );
            logger.info("测试文件删除成功");

            logger.info("MinIO 客户端测试完成，连接正常");
        } catch (Exception e) {
            logger.error("MinIO 客户端测试失败: {}", e.getMessage(), e);
        }
    }
} 